﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Sugar;

namespace Medianamik.UI.Controls
{
    public class InterfacePicker : CompositeControl
    {
        readonly Repeater _repeater = new Repeater();
        private const string _implementedControlId = "InterfacePickerImplemented";
        private const string _interfaceIdControlId = "InterfacePickerInterfaceId";

        public string OnClientValidate
        {
            get
            {
                var onClientValidate = ViewState["OnClientValidate"];
                return onClientValidate == null ? "" : onClientValidate.ToString();
            }
            set
            {
                ViewState["OnClientValidate"] = value;
            }
        }

        protected bool DataBound
        {
            get
            {
                return (bool?)ViewState["DataBound"] ?? false;
            }
            set
            {
                ViewState["DataBound"] = value;
            }
        }

        public virtual IEnumerable<NodeTypeInterface> DataSource { get; set; }

        public virtual IEnumerable<Guid> SelectedInterfaceIds
        {
            get
            {
                EnsureChildControls();

                foreach (RepeaterItem item in _repeater.Items)
                {
                    var implemented = item.FindControl(_implementedControlId) as CheckBox;
                    var strInterfaceId = item.FindControl(_interfaceIdControlId) as HiddenField;
                    Guid interfaceId;

                    if (implemented != null && strInterfaceId != null && implemented.Checked &&
                        StringHelper.IsGuid(strInterfaceId.Value, out interfaceId))
                        yield return interfaceId;
                }
            }
            set
            {
                EnsureChildControls();

                foreach (RepeaterItem item in _repeater.Items)
                {
                    var implemented = item.FindControl(_implementedControlId) as CheckBox;
                    var strInterfaceId = item.FindControl(_interfaceIdControlId) as HiddenField;
                    Guid interfaceId;

                    if (implemented != null && strInterfaceId != null &&
                                            StringHelper.IsGuid(strInterfaceId.Value, out interfaceId))
                    {
                        implemented.Checked = value.Contains(interfaceId);
                    }
                }
            }
        }

        public Guid? NodeTypeId
        {
            get
            {
                object o = ViewState["NodeTypeId"];
                if (o == null)
                    return null;
                return (Guid)o;
            }
            set { if (value != null) { ViewState["NodeTypeId"] = value; } }
        }

        public override void DataBind()
        {
            base.DataBind();
            DataBound = true;
        }

        /// <summary>
        /// Création de la hierarchie de contrôles
        /// </summary>
        protected override void CreateChildControls()
        {
            Controls.Add(_repeater);
            _repeater.ItemTemplate = new InterfacePickerItemTemplate(OnClientValidate, _implementedControlId,
                _interfaceIdControlId, NodeTypeId);
            _repeater.HeaderTemplate = new InterfacePickerHeaderTemplate();
            _repeater.FooterTemplate = new InterfacePickerFooterTemplate();

            if (!DataBound)
            {
                _repeater.DataSource = DataSource;
                _repeater.DataBind();
                _repeater.Visible = _repeater.Items.Count > 0;
            }
        }

        public class InterfacePickerItemTemplate : ITemplate
        {
            private  CheckBox _implemented;
            private  HiddenField _interfaceId;
            private HyperLink _link;
            private readonly string _implementedControlId;
            private readonly string _interfaceIdControlId;
            private readonly string _onClientValidate;
            private readonly NodeType _type;

            public InterfacePickerItemTemplate(string onClientValidate, string implementedControlId, 
                string interfaceIdControlId, Guid? typeId)
            {
                _onClientValidate = onClientValidate;
                _implementedControlId = implementedControlId;
                _interfaceIdControlId = interfaceIdControlId;

                if (typeId.HasValue)
                    _type = NodeTypeManager.GetNodeType(typeId.Value);
            }

            void ImplementedDataBinding(object sender, EventArgs e)
            {
                var container = (RepeaterItem)_implemented.NamingContainer;
                var interf = container.DataItem as NodeTypeInterface;

                if (interf != null)
                {
                    _implemented.Text = interf.Name;
                    if (_type != null && !_type.RespectsInterface(interf))
                        _implemented.CssClass = "TxtErreur";
                    _interfaceId.Value = interf.ID.ToString();

                    if(!String.IsNullOrEmpty(_onClientValidate))
                        _link.Attributes.Add("onclick", _onClientValidate + "('" + interf.ID + "')");
                }
            }

            public void InstantiateIn(Control container)
            {
                container.Controls.Add(new LiteralControl("<tr><td style=\"padding-right:10px; vertical-align:middle;\">"));

                _interfaceId = new HiddenField();
                container.Controls.Add(_interfaceId);
                _interfaceId.ID = _interfaceIdControlId;

                _implemented = new CheckBox();
                container.Controls.Add(_implemented);
                _implemented.ID = _implementedControlId;
                _implemented.DataBinding += ImplementedDataBinding;

                container.Controls.Add(new LiteralControl("</td><td>"));

                _link = new HyperLink();
                container.Controls.Add(_link);
                _link.Text = "info";
                _link.NavigateUrl = "#";

                container.Controls.Add(new LiteralControl("</td></tr>"));
            }

        }

        public class InterfacePickerHeaderTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                container.Controls.Add(new LiteralControl("<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" class=\"TableauFormulaire\">"));
            }

        }

        public class InterfacePickerFooterTemplate : ITemplate
        {
            public void InstantiateIn(Control container)
            {
                container.Controls.Add(new LiteralControl("</table>"));
            }
        }
    }
}